package com.qdxwx.web.controller.user;

import com.qdxwx.common.constants.CacheConstants;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKRequest;
import com.qdxwx.data.service.account.UserAccountDetailService;
import com.qdxwx.data.service.account.UserAccountService;
import com.qdxwx.data.service.coupon.CouponCodeService;
import com.qdxwx.data.service.order.OrderService;
import com.qdxwx.models.account.UserAccount;
import com.qdxwx.models.account.UserAccountDetail;
import com.qdxwx.models.coupon.CouponCode;
import com.qdxwx.models.enums.AccountBizType;
import com.qdxwx.models.enums.AccountHistoryType;
import com.qdxwx.models.enums.AccountType;
import com.qdxwx.models.enums.OrderStatus;
import com.qdxwx.models.order.Order;
import com.qdxwx.models.order.OrderQuery;
import com.qdxwx.models.order.OrderVO;
import com.qdxwx.models.user.User;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 前台订单
 * @author developer
 */
@Controller
@RequestMapping("/user/order")
public class UserOrderController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(UserOrderController.class);

	@Autowired
	private OrderService orderService;
	@Autowired
	private CouponCodeService couponCodeService;
	@Autowired
	private UserAccountService userAccountService;
	@Autowired
	private UserAccountDetailService userAccountDetailService;

	/**
	 * 我的订单列表
	 */
	@RequestMapping("/list.html")
	public String myOrderList(HttpServletRequest request, ModelMap mmap) {
		User user = LoginUser.getUser(request);
		if (user == null) {
			return VIEW_ERROR_403;
		}
		OrderStatus state = OrderStatus.get(request.getParameter("state"));

		int currentPage = TKConvert.toInteger(request.getParameter("page"));
		PageRequest page = new PageRequest();
		page.setCurrentPage(currentPage);
		page.setPageSize(5);
		OrderQuery orderQuery = new OrderQuery();
		orderQuery.setUserId(user.getUserId());
		/*如果不是查看全部set查询条件*/
		if (state != null) {
			orderQuery.setStatus(state.toString());
		}
		long total = orderService.count(orderQuery);
		mmap.put("totalPages", page.getTotalPages(total));
		List<OrderVO> orderList = orderService.getListForUc(orderQuery, page);
		mmap.put("orderList", orderList);
		mmap.put("queryOrder", orderQuery);
		mmap.put("page", page);
		mmap.put("user",user);
		if(TKRequest.isMobileBrowse(request)){
			return getViewPathH5("user/uc-order-list");
		}
		return getViewPath("ucenter/uc-order-list");
	}

	/**
	 * 取消订单
	 */
	@RequestMapping("/cancel.json")
	@ResponseBody
	public AjaxResult cancelOrder(HttpServletRequest request) {
		User user = LoginUser.getUser(request);
		if (user == null) {
			return AjaxResult.auth("请登录后操作");
		}
		int orderId = TKConvert.toInteger(request.getParameter("orderId"));
		Order order = orderService.get(orderId);
		if (order == null) {
			return AjaxResult.notFound("找不到指定订单！");
		}
		if (order.getUserId() != user.getUserId()) {
			return AjaxResult.notFound("找不到指定订单！");
		}
		if (!OrderStatus.INIT.equals(order.getStatus())) {
			return AjaxResult.error("此订单不允许取消！");
		}
		order.setStatus(OrderStatus.CANCEL.toString());
		int count = orderService.updateState(order);
		if (count > 0) {
			//返还被扣款
			if (order.getVmAmount() > 0 || order.getBackAmount() > 0) {
				UserAccount account = userAccountService.getByUserId(order.getUserId());

				account.credit(order.getBackAmount(), AccountType.BACK);
				account.credit(order.getVmAmount(), AccountType.VM);

				// 每次充值都有out_trade_no，防止重复充值做查询判断
				// 查询账户历史是否用out_trade_no，如果有了。抛出异常
	/*			UserAccountDetail accountHistory = userAccountDetailService.getByOrderId(order.getOrderId(), order.getUserId());
				if (accountHistory != null) {
					throw new AccountException("此订单已经存在资金操作记录！");
				}*/
				userAccountService.update(account);
				// 添加账户历史操作记录
				UserAccountDetail accountHistory = new UserAccountDetail();
				accountHistory.setUserId(order.getUserId());
				accountHistory.setOrderId(orderId);// 订单id
				accountHistory.setIsDisplay(0);
				accountHistory.setBalance(account.getBalance());// 当前余额
				accountHistory.setVmAmount(account.getVmAmount());// vm余额
				accountHistory.setBackAmount(account.getBackAmount());// 提现余额
				accountHistory.setOrderAmount(order.getVmAmount() + order.getBackAmount());// 交易金额
				accountHistory.setDescription("订单取消"+order.getOrderNo());// 账户历史内容描述
				accountHistory.setActHistoryType(AccountHistoryType.CASHLOAD.toString());// 帐务历史类型.充值。消费等
				accountHistory.setBizType(AccountBizType.CASH.toString());// 业务类型(课程订单、会员订单、图书订单)
				accountHistory.setVersion(account.getVersion());// 乐观锁版本号
				userAccountDetailService.insert(accountHistory);
			}
			// 查询优惠券编码 解冻
			if ("ON".equals(CacheConstants.COUPON_IS_OPEN) && order.getCouponCodeId() > 0) {
				CouponCode couponCodeTemp = couponCodeService.get(order.getCouponCodeId());
				if (couponCodeTemp != null && couponCodeTemp.getStatus() == 6) {//冻结才修改
					couponCodeTemp.setStatus(1);//1未使用
					couponCodeTemp.setOrderNo("");
					couponCodeTemp.setOrderId(0);
					couponCodeService.update(couponCodeTemp);
				}
			}
			return AjaxResult.success();
		} else {
			return AjaxResult.error("取消失败！");
		}
	}
}
